package com.sc.pattern.readwrite;

import java.util.Random;

/**
 * Created  on 2018/1/7.
 *
 * @author sc
 */
public class WriteWorker extends Thread{

    private static final Random random = new Random(System.currentTimeMillis());
    private final SharedData data;
    private final  String filter;
    private int index = 0;

    public WriteWorker(SharedData data,String filter){
        this.filter =filter;
        this.data =data;
    }


    @Override
    public void run() {
        while (true){
            char c = nextChar();
            data.Write(c);
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private char nextChar(){
        char c = filter.charAt(index);
        index++;
        if(index>=filter.length()){
            index=0;
        }
        return c;
    }
}
